<template>
    <n-card class="search-form">
        <SearchForm
            :items="searchFormItems"
            v-model:value="tableConfig.params!"
        >
            <template #tool> </template>
        </SearchForm>
    </n-card>

    <n-card title="分组管理">
        <template #header-extra>
            <TableTool @add="onEdit" />
        </template>
        <Table ref="tableRef" :config="<any>tableConfig" />
    </n-card>

    <ModalForm
        :items="formItems"
        v-model:show="formShow"
        v-model:value="formState"
        @submit="onSubmit"
        :loading="submiting"
        style="width: 600px"
        :form-props="{
            labelWidth: '6rem'
        }"
    />

    <SetFieldsDrawer v-model:show="show" :hash-id="hashId" />
</template>

<script setup lang="ts">
import {
    coreHashAdd,
    coreHashDelete,
    coreHashList,
    coreHashUpdate
} from '@/apis/core/hash'
import { DeleteButton, EditButton } from '@/components/button'
import { FormItemsConfig, ModalForm } from '@/components/form'
import { Table, TableConfig, TableTool } from '@/components/table'
import useState from '@/hooks/useState'
import {
    ICoreHashListParameter,
    ICoreHash,
    ICoreHashEditParameter
} from '@/types/core/hash'
import {
    NSpace,
    DataTableInst,
    useMessage,
    NButton,
    NTag,
    NIcon
} from 'naive-ui'
import { computed, h, nextTick, ref, watch } from 'vue'
import { useRequest } from 'vue-request'
import {
    hashMethodOptions,
    hashNeedLoginOptions,
    hashNeedLogOptions,
    hashNeedSystemOptions,
    hashStateOptions
} from '../options'
import { useClipboard } from '@vueuse/core'
import {
    CopyAllRound,
    BlockRound,
    PersonPinOutlined,
    ScreenLockPortraitFilled
} from '@vicons/material'
import { coreGroupList } from '@/apis/core/group'
import SetFieldsDrawer from './SetFieldsDrawer.vue'

const message = useMessage()

const props = defineProps({
    appId: {
        type: Number,
        required: true
    }
})

/**
 * 分组
 */
const { loading: groupListLoading, data: groupListData } = useRequest(
    coreGroupList,
    {
        onSuccess(res) {
            if (res.length) {
                const groupId = res[0].id
                tableConfig.value.params.group_id = groupId
                tableRef.value?.run({
                    group_id: groupId
                })
            } else {
                tableConfig.value.params.group_id = null
            }
        }
    }
)

/**
 * 搜索
 */
const searchFormItems = computed<FormItemsConfig<ICoreHashListParameter>>(
    () => {
        return [
            {
                field: 'group_id',
                label: '分组',
                component: 'Select',
                props: {
                    placeholder: '请选择分组',
                    options: groupListData.value?.map((item) => ({
                        label: item.name,
                        value: item.id
                    })),
                    loading: groupListLoading.value
                }
            }
        ]
    }
)

/**
 * 表格
 */
// 复制
const { copy, isSupported } = useClipboard()
function toCopy(val: string) {
    if (isSupported.value) {
        copy(val)
        message.info('复制成功')
    } else {
        message.error('当前浏览器不支持该复制功能')
    }
}
const tableRef = ref<DataTableInst>()
const tableConfig = ref<TableConfig<ICoreHash>>({
    service: coreHashList,
    auto: false,
    params: {
        app_id: props.appId,
        group_id: null
    },
    columns: [
        {
            title: 'ID',
            key: 'id'
        },
        {
            title: '名称',
            key: 'name',
            render(rowData) {
                return h('span', { style: 'font-weight: 600' }, rowData.name)
            }
        },
        {
            title: '哈希',
            key: 'hash',
            render(rowData) {
                return h(
                    NSpace,
                    { align: 'center' },
                    {
                        default: () => [
                            h('span', {}, rowData.hash),
                            h(NButton, {
                                size: 'tiny',
                                type: 'info',
                                quaternary: true,
                                renderIcon() {
                                    return h(
                                        NIcon,
                                        {},
                                        { default: () => h(CopyAllRound) }
                                    )
                                },
                                onClick() {
                                    toCopy(rowData.hash)
                                }
                            })
                        ]
                    }
                )
            }
        },
        {
            title: '控制器方法',
            key: 'action'
        },
        {
            title: '请求方法',
            key: 'method',
            render(rowData) {
                return h(
                    NTag,
                    {
                        size: 'small',
                        type: rowData.method === 'POST' ? 'info' : 'warning'
                    },
                    {
                        default: () => rowData.method
                    }
                )
            }
        },
        {
            title: '热度',
            key: 'visits'
        },
        {
            title: '系统级验证',
            key: 'need_system',
            render(rowData) {
                return h(
                    NTag,
                    {
                        type: rowData.need_system === 1 ? 'success' : 'error',
                        bordered: false,
                        size: 'small'
                    },
                    {
                        default: () =>
                            rowData.need_system === 1 ? '安全' : '危险',
                        icon: () =>
                            h(
                                NIcon,
                                {},
                                {
                                    default: () =>
                                        h(
                                            rowData.need_system === 1
                                                ? ScreenLockPortraitFilled
                                                : BlockRound
                                        )
                                }
                            )
                    }
                )
            }
        },
        {
            title: '登录验证',
            key: 'need_login',
            render(rowData) {
                return h(
                    NTag,
                    {
                        type: rowData.need_login === 1 ? 'success' : 'error',
                        bordered: false,
                        size: 'small'
                    },
                    {
                        default: () =>
                            rowData.need_login === 1 ? '安全' : '危险',
                        icon: () =>
                            h(
                                NIcon,
                                {},
                                {
                                    default: () =>
                                        h(
                                            rowData.need_login === 1
                                                ? PersonPinOutlined
                                                : BlockRound
                                        )
                                }
                            )
                    }
                )
            }
        },
        {
            key: 'state',
            title: '状态',
            render(rowData) {
                const state = hashStateOptions.find(
                    (item) => item.value === rowData.state
                )
                return h(
                    NTag,
                    { size: 'small', type: state?.theme, bordered: false },
                    { default: () => state?.label }
                )
            }
        },
        {
            title: '操作',
            key: '_actions',
            width: 220,
            render(rowData) {
                return h(
                    NSpace,
                    {},
                    {
                        default: () => [
                            h(DeleteButton, {
                                service: () =>
                                    coreHashDelete({ id: rowData.id }),
                                onDone: () => tableRef.value?.run(),
                                buttonProps: {
                                    // @ts-ignore
                                    disabled: rowData._protect
                                }
                            }),
                            h(EditButton, {
                                onClick: () => onEdit(rowData)
                            }),
                            h(
                                NButton,
                                {
                                    size: 'tiny',
                                    type: 'warning',
                                    onClick: () => setFields(rowData.id)
                                },
                                { default: () => '设置字段' }
                            )
                        ]
                    }
                )
            }
        }
    ]
})

watch(
    () => tableConfig.value.params.group_id,
    (val) => {
        if (val) {
            tableRef.value?.run({
                app_id: null,
                group_id: val
            })
        } else {
            tableRef.value?.run({
                app_id: props.appId,
                group_id: null
            })
        }
    }
)

/**
 * 编辑
 */
const formItems = computed<FormItemsConfig<ICoreHashEditParameter>>(() => {
    return [
        {
            field: 'group_id',
            label: '所属分组',
            component: 'Select',
            props: {
                placeholder: '请选择分组',
                options: groupListData.value?.map((item) => ({
                    label: item.name,
                    value: item.id
                }))
            },
            rule: { required: true }
        },
        {
            field: 'name',
            label: '名称',
            component: 'Input',
            props: {
                placeholder: '接口名称'
            },
            rule: { required: true, min: 2, max: 20 }
        },
        {
            field: 'hash',
            label: '哈希',
            component: 'Input',
            props: {
                placeholder: '自动生成',
                disabled: true
            }
        },
        {
            field: 'action',
            label: '控制器方法',
            component: 'Input',
            props: {
                placeholder: '服务端控制器方法'
            },
            rule: { required: true }
        },
        {
            field: 'method',
            label: '请求方法',
            component: 'RadioGroup',
            props: {
                options: hashMethodOptions,
                'default-value': 'POST'
            }
        },
        {
            field: 'sort',
            label: '排序',
            component: 'InputNumber',
            props: {
                min: 1,
                max: 9999,
                precision: 0
            },
            rule: { min: 1, max: 9999, type: 'integer' }
        },
        {
            field: 'state',
            label: '状态',
            component: 'RadioGroup',
            props: {
                options: hashStateOptions,
                'default-value': 1
            }
        },
        {
            field: 'need_system',
            label: '系统级验证',
            component: 'RadioGroup',
            props: {
                options: hashNeedSystemOptions,
                'default-value': 1
            }
        },
        {
            field: 'need_login',
            label: '用户级验证',
            component: 'RadioGroup',
            props: {
                options: hashNeedLoginOptions,
                'default-value': 1
            }
        },
        {
            field: 'need_log',
            label: '记录日志',
            component: 'RadioGroup',
            props: {
                options: hashNeedLogOptions,
                'default-value': 1
            }
        },
        {
            field: 'remark',
            label: '备注',
            component: 'Input',
            props: {
                type: 'textarea',
                placeholder: '记录点儿什么',
                autosize: true
            }
        }
    ]
})
const defaultState: ICoreHashEditParameter = {
    group_id: null as any,
    name: '',
    hash: '',
    action: '',
    method: 'POST',
    need_system: 1,
    need_login: 1,
    state: 1,
    sort: null as any,
    remark: '',
    need_log: 1
}
const formState = ref<ICoreHashEditParameter>({ ...defaultState })
const formShow = ref(false)
function onEdit(rowData?: ICoreHash) {
    formShow.value = true
    nextTick(() => {
        if (rowData) {
            formState.value = { ...rowData }
        } else {
            formState.value = { ...defaultState }
        }
    })
}

const { state: submiting, setState: setSubmiting } = useState()
function onSubmit() {
    setSubmiting(true)
    const API = formState.value.id ? coreHashUpdate : coreHashAdd
    API(formState.value)
        .then(() => {
            formShow.value = false
            tableRef.value?.run()
            message.success('操作成功')
        })
        .catch((e: Error) => {
            message.error(e.message)
        })
        .finally(() => setSubmiting(false))
}

/**
 * 设置字段
 */
const hashId = ref<number>()
const { state: show, setState: setShow } = useState()
function setFields(id: number) {
    hashId.value = id
    setShow(true)
}
</script>
